package com.ncloud.crm.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.ncloud.common.enmus.ResultEnum;
import com.ncloud.common.exception.UserException;
import com.ncloud.common.utils.PageHelperUtils;
import com.ncloud.crm.common.Constant;
import com.ncloud.crm.entity.BsCust;
import com.ncloud.crm.entity.order.Order;
import com.ncloud.crm.mapper.OrderMapper;
import com.ncloud.crm.service.BsCustService;
import com.ncloud.crm.service.BsProjectService;
import com.ncloud.crm.service.OrderCustomerService;
import com.ncloud.crm.service.OrderService;
import com.ncloud.crm.utils.DateUtils;
import com.ncloud.crm.utils.OrderNodeDefineUtils;
import com.ncloud.crm.utils.TableIdDefineUtils;
import com.ncloud.param.service.SequenceService;

@Service
public class OrderServiceImpl implements OrderService {
	
	private static final Logger logger = LogManager.getLogger(OrderServiceImpl.class);
	
	@Autowired
	private OrderMapper orderMapper;
	@Reference
	private SequenceService sequenceService;
	@Autowired
	private OrderFinishServiceImpl finishService;
	@Autowired
	private OrderCustomerService orderCustomerService;
	@Autowired
	private BsCustService bsCustService;
	@Autowired
	private BsProjectService bsProjectService;
	@Override
	public Order getOrderPk(Long orderId) {
		Order order = orderMapper.getOrderPk(orderId);
		return order;
	}
	
	@Override
	public Order getHisOrderPK(Long orderId) {
		Order order = orderMapper.getHisOrderPk(orderId);
		return order;
	}

	@Override
	public JSONObject insertOrder(JSONObject json) throws UserException{
		Order order = JSON.parseObject(json.toJSONString(),Order.class);
		try {
			validation(order);
			orderMapper.insertOrder(order);
		}catch (RuntimeException e){
			e.printStackTrace();
			throw new UserException(ResultEnum.DATABASE_ERROR);
		}
		return json;
	}

	private void validation(Order order){
		if(order.getOrderId() == null){
			Long id = sequenceService.getSequence("order_id_seq");
			order.setOrderId(id);
			logger.info(id);
		}else{

		}
	}

	@Override
	public Object getOrderList(JSONObject json) {
		if(!json.containsKey("userID")){
			throw new UserException("2001","传入参数有误");
		}
		Object object = null;
		PageInfo pageInfo=null;
		List<Map<Object,Object>> myOrderList=new ArrayList<Map<Object,Object>>();
		Long userId=null;
		if(json.containsKey("userID")){
			userId=json.getLong("userID");
		}
		String custName=null;
		if(json.containsKey("custName")){
			custName=json.getString("custName");
		}
		String orderState=null;
		if(json.containsKey("orderState")){
			orderState=json.getString("orderState");
		}
		
		if(PageHelperUtils.isPage(json)){
			PageHelperUtils.setPageParam(json);
			myOrderList = orderMapper.getMyOrderListByCreateUser(userId,custName,orderState);
			pageInfo=new PageInfo(myOrderList);
			object = JSON.parseObject(JSON.toJSONString(pageInfo));
		}else {
			myOrderList=orderMapper.getMyOrderListByCreateUser(userId,custName,orderState);
			object = JSON.parseArray(JSON.toJSONString(myOrderList));
		}
		
		return object;	
	}
	
	@Override
	public Object getAllOrderList(JSONObject json){
		Object object = null;
		List<Map<String,Object>> allOrderList=new ArrayList<Map<String,Object>>();
		Long chnlId = json.containsKey("chnlId")?json.getLong("chnlId"):null;
		String custName = json.containsKey("custName")?json.getString("custName"):"";
		String orderState = json.containsKey("orderState")?json.getString("orderState"):"0";
		if(PageHelperUtils.isPage(json)){
			PageHelperUtils.setPageParam(json);
			allOrderList = orderMapper.getAllOrderList(chnlId,custName,orderState);
			logger.info("param="+chnlId+","+custName+","+orderState+";allOrderList="+allOrderList);
			@SuppressWarnings({ "rawtypes", "unchecked" })
			PageInfo pageInfo=new PageInfo(allOrderList);
			logger.info("pageInfo="+pageInfo);
			object = JSON.parseObject(JSON.toJSONString(pageInfo));
		}else {
			allOrderList=orderMapper.getAllOrderList(chnlId,custName,orderState);
			object = JSON.parseArray(JSON.toJSONString(allOrderList));
		}
		
		return object;	
	}

	@Override
	public JSONObject getPk(JSONObject json) {
		return null;
	}

	@Override
	public JSONObject insert(JSONObject json) {
		return null;
	}
	
	
	
	@Override
	public JSONObject validate(JSONObject json,JSONObject result) {
		logger.info("原始订单集合信息：{}"+json.toJSONString());
		JSONObject order = new JSONObject();
		if(json==null || json.isEmpty()){
			throw new UserException(ResultEnum.ORDER_INFO_ERROR);
		}

		if(json.containsKey(OrderNodeDefineUtils.ORDER)){

			String orderDate = DateUtils.getDateTime();
			order = json.getJSONObject(OrderNodeDefineUtils.ORDER);
			if(json.containsKey(OrderNodeDefineUtils.ORDER_CUSTOMER)){
				JSONObject customer = json.getJSONObject(OrderNodeDefineUtils.ORDER_CUSTOMER);
				if(customer.containsKey("custName")){
					result.put("custName",customer.getString("custName"));
					order.put("custName",customer.getString("custName"));
				}
			}else{
				if(order.containsKey("custId")){
					BsCust cust = bsCustService.getCustInfoById(order.getLong("custId"));
					order.put("custName",cust.getCustName());
				}else{
					throw new UserException(ResultEnum.ORDER_INFO_ERROR.getCode(),"订单客户id不存在！");
					/*//客户id不存在，根据项目id获取信息
					if(order.containsKey("projectId")){
						BsProject project = bsProjectService.getProjectInfo(order.getLong("projectId"));
						order.put("projectName",project.getProjectName());
						*//*custname *//*
						BsCust cust = bsCustService.getCustInfoById(project.getCustId());
						if(cust !=null){
							order.put("custId",project.getCustId());
							order.put("custName",cust.getCustName());
						}else{
							throw new UserException(ResultEnum.ORDER_INFO_ERROR.getCode(),"不存在当前客户："+project.getCustId());
						}

					}else{
						throw new UserException(ResultEnum.ORDER_INFO_ERROR.getCode(),"订单客户id不存在！");
					}*/
				}
			}

				/*产品*/
			if(json.containsKey(OrderNodeDefineUtils.ORDER_PRODUCT)){
				JSONObject project = json.getJSONObject(OrderNodeDefineUtils.ORDER_PRODUCT);
				if(project.containsKey("prodId")){
					//result.put("prodId",project.getString("prodId"));
					order.put("prodId",project.getString("prodId"));
				}else{
					throw new UserException(ResultEnum.ORDER_INFO_ERROR.getCode(),"订单产品ID不存在{prodId}！");
				}
			}
			/*生成orderId*/
			if(!order.containsKey(TableIdDefineUtils.ORDER_ID) || StringUtils.isEmpty(order.getString(TableIdDefineUtils.ORDER_ID))){
				Long id = sequenceService.getSequence("seq_order_id");
				order.put(TableIdDefineUtils.ORDER_ID,id);
				result.put(TableIdDefineUtils.ORDER_ID,id);
			}else{
				result.put(TableIdDefineUtils.ORDER_ID,order.getLong(TableIdDefineUtils.ORDER_ID));
			}
			/*生成custId*/
			if(!order.containsKey(TableIdDefineUtils.CUST_ID) || StringUtils.isEmpty(order.getString(TableIdDefineUtils.CUST_ID))){
				if(json.containsKey(OrderNodeDefineUtils.ORDER_CUSTOMER)){
					JSONObject customerOrder= json.getJSONObject(OrderNodeDefineUtils.ORDER_CUSTOMER);
					String modifyTag = customerOrder.getString("modifyTag");
					if(modifyTag.equals(Constant.ADD)){
						Long id = sequenceService.getSequence("seq_cust_id_seq");
						order.put(TableIdDefineUtils.CUST_ID,id);
						result.put(TableIdDefineUtils.CUST_ID,id);
						/*Long customerId = orderCustomerService.getCustId(customerOrder.getString("companyCode"));
						*//*如果已经存在客户，就不在生成客户信息和账户信息*//*
						if(customerId !=null){
							order.put(TableIdDefineUtils.CUST_ID,customerId);
							result.put(TableIdDefineUtils.CUST_ID,customerId);
						}else{
							Long id = sequenceService.getSequence("seq_cust_id_seq");
							order.put(TableIdDefineUtils.CUST_ID,id);
							result.put(TableIdDefineUtils.CUST_ID,id);
						}*/
					}
				}

			}else{
				result.put(TableIdDefineUtils.CUST_ID,order.getLong(TableIdDefineUtils.CUST_ID));
			}
				/*生成项目编码*/
			/*if(!order.containsKey(TableIdDefineUtils.PROJECT_ID) || StringUtils.isEmpty(order.getString(TableIdDefineUtils.PROJECT_ID))){
				Long id = sequenceService.getSequence("seq_project_id");
				order.put(TableIdDefineUtils.PROJECT_ID,id);
				result.put(TableIdDefineUtils.PROJECT_ID,id);
			}else{
				result.put(TableIdDefineUtils.PROJECT_ID,order.getLong(TableIdDefineUtils.PROJECT_ID));
			}*/
			//初始化订单
			order.put("orderState", Constant.ORDER_STATE_DOING);
			//创建时间
			order.put("createDate",orderDate);
			//设置人员
			order.put("createUser",json.getLong("userId"));
			result.put("userId",json.getLong("userId"));
			//设置受理渠道
			order.put("channelId",1);
			//设置时间
			//设置创建时间
			result.put("createTime", orderDate);
		}
		logger.info("订单信息:{}"+order.toJSONString());
		return order;
	}
	
	@Override
	public JSONObject finishOrder(Long orderId) {
		//获取订单信息
		Order order = getOrderPk(orderId);
		if(order!=null){
			//调用完工服务处理资料落地
			finishService.finishOrder(orderId);
			//转移订单信息到历史表中
			//转移工单信息到历史表中
		}
		return null;
	}

	@Override
	public int updateOrderState(Order order) {
		return orderMapper.updateOrderState(order);
	}

	@Override
	public Long getOrderNoWorkInfo(Long orderId) {
		return orderMapper.getOrderNoWorkInfo(orderId);
	}

	@Override
	public void moveOrder2His(Long orderId) {
		orderMapper.insertHisOrder(orderId);
	}

	@Override
	public int deleteByOrderId(Long orderId) {
		return orderMapper.deleteByOrderId(orderId);
	}

	@Override
	public List<Map<String, Object>> getNeedConstructOrders() {
		List<Map<String, Object>> orderList = orderMapper.getNeedConstructOrders();
		return orderList;
	}

}
